<?php
namespace api\modules\openapi\models\uc;
/**
 * Created by JetBrains PhpStorm.
 * User: gary
 * Date: 11/15/14
 * Time: 7:53 AM
 * To change this template use File | Settings | File Templates.
 */
use Yii;
class UcLib {
    // UC配置
    protected $conf;
    // UC同步基础地址
    protected $base_url = '';
    protected $base_url_new = '';
    // UC同步地址
    protected $url = '';
    // 请求UC接口,链接超时时间设置
    private $connect_timeout;
    // 请求UC接口,执行超时时间设置
    private $request_timeout;
    
    public function __construct() {
        $this->conf = Yii::$app->params['UC_API_CONF'];
        $this->base_url = $this->conf['BASE_URL'];
        $this->base_url_new = $this->conf['BASE_URL_NEW'];
        $this->connect_timeout = $this->conf['CONNECT_TIMEOUT'];
        $this->request_timeout = $this->conf['REQUEST_TIMEOUT'];
        $this->url = $this->base_url . $this->conf['SEGMENT_URL'];
    }
    
    /**
     * 处理返回的头信息
     * @param $header
     * @return array
     */
    private function doHeader($header) {
        $arr_return = array();
        
        foreach ($header as $h) {
            if (strpos($h, ': ')) {
                list($key, $value)  = explode(': ', $h);
                $arr_return[$key] = $value;
            }
        }
        
        return $arr_return;
    }
    
    /**
     * Get获取记录列表
     * @param $url
     * @return mixed
     */
    private function curl_get_list($url) {
        $body = file_get_contents($url);
        $arr_header = $http_response_header;
        $map_header = $this->doHeader($arr_header);
        $body = json_decode($body, true);
        
        return array($map_header, $body);
    }
    
    
    /**
     * 查询列表
     * @param $params
     * @param $filters
     * @param $sort
     * @return mixed
     */
    public function getList($params, $filters, $sort) {
        $str_query = http_build_query($params);
        $this->url .= '?' . $str_query;
        
        if (!empty($filters)) {
            $this->url .= '&filters=' . json_encode($filters);
        }
        if (!empty($sort)) {
            $this->url .= '&sort=' . json_encode($sort);
        }
        
        list($map_header, $arr_result) = $this->curl_get_list($this->url);
        
        if (0 === $arr_result['status']) {
            $arr_result = $arr_result['response'];
        }
        
        return array($map_header, $arr_result);
    }
    
    /**
     * 根据ID列表，获取数据
     * @param $arr_id
     * @return array
     */
    public function getListByIds($arr_id) {
        $ids = array();
        foreach ($arr_id as $id) {
            $ids[] = intval($id);
        }
        $params = array(
            'id' => array('$in' => $ids)
        );
        $this->url .= '?filters=' . json_encode($params);
        list($map_header, $arr_result) = $this->curl_get_list($this->url);
        
        if (0 === $arr_result['status']) {
            $arr_result = $arr_result['response'];
        }
        
        return $arr_result;
    }
}